import React, {PureComponent} from 'react';
import BaseComponent from '../base/BaseComponent';
import {connect} from 'react-redux';
import {
  StyleSheet,
  ImageBackground,
  Platform,
  Text,
  Button,
  TextInput,
  View,
  FlatList,
  RefreshControl,
  TouchableOpacity,
  Image,
  Keyboard,
} from 'react-native';
import {TextButton} from '../../components/Button';
import I18n from 'react-native-i18n';
import {NormalHeader} from '../../components/NavigationHeader';
import {createChannel} from '../../api/channel/index';
import Web3 from 'web3';
import WalletUtils from '../../utils/wallet/WalletUtils';

class HecoScreen extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      result: '',
      address: props.userInfo.address,
      privateKey: '',
    };
  }

  async componentDidMount() {
    super.componentDidMount();

    // https://http-testnet-node.huobichain.com
    const web3 = new Web3('https://http-testnet.hecochain.com');
    // const web3 = new Web3('https://http-mainnet.hecochain.com');
    let chainId = await web3.eth.getChainId();
    console.log(`chain id: ${chainId}`);
  }

  generalAccount = async () => {
    let obj = await WalletUtils.generalWallet('123456');
    this.setState({
      result: JSON.stringify(obj),
    });
  };

  queryBalance = async () => {
    Promise.all([
      WalletUtils.queryTokenBalance(
        this.props.userInfo.address,
        '0x156b250a12003dB9483bD0DF18989B39C05CBD1d',
        18,
      ),
      WalletUtils.queryAccountHecoBalance(this.props.userInfo.address),
    ]).then((res) => {
      console.log(res);
      this.setState({
        result: JSON.stringify({
          token: res[0],
          heco: res[1],
        }),
      });
    });
  };

  transferHeco = async () => {
    let pk = await WalletUtils.privateKeyOfKeystore(
      this.props.userInfo.keystore,
      'q',
    );
    WalletUtils.transferHeco(
      pk,
      '0xb9a7405BaCA796325440B183BC3390F66927c583',
      '0.007',
      (hash) => {
        this.setState({
          result: '交易已发送，正在监听交易->' + hash,
        });
      },
    )
      .then((res) => {
        console.log('交易已确认' + JSON.stringify(res, null, 2));
        this.setState({
          result: '交易已上链',
        });
      })
      .catch((err) => {
        this._showAlert({content: err + ''});
      });
  };

  getPrivateKey = async () => {
    let pk = await WalletUtils.privateKeyOfKeystore(
      this.props.userInfo.keystore,
      'q',
    );

    this.setState({
      result: pk,
    });
  };

  transferErc20 = async () => {
    let pk = await WalletUtils.privateKeyOfKeystore(
      this.props.userInfo.keystore,
      'q',
    );

    WalletUtils.transferErc20(
      pk,
      '0xb9a7405BaCA796325440B183BC3390F66927c583',
      '77',
      '0x156b250a12003dB9483bD0DF18989B39C05CBD1d',
      18,
      (hash) => {
        this.setState({
          result: '交易已发送，正在监听交易->' + hash,
        });
      },
    )
      .then((res) => {
        console.log('交易已确认' + JSON.stringify(res, null, 2));
        this.setState({
          result: '交易已上链',
        });
      })
      .catch((err) => {
        this._showAlert(err + '');
      });
  };

  renderComponent = () => {
    return (
      <View style={{backgroundColor: '#FFCB26', flex: 1, padding: 0}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="heco链测试"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <View style={{padding: 20}}>
          <Text>{'账户：' + this.state.address}</Text>
          <Text style={{minHeight: 200}}>
            {'操作结果：\n' + this.state.result}
          </Text>
          <TextButton text="生成账户" onPress={this.generalAccount} />
          <TextButton text="获取账户私钥" onPress={this.getPrivateKey} />
          <TextButton text="获取账户余额信息" onPress={this.queryBalance} />
          <TextButton text="发送heco币" onPress={this.transferHeco} />
          <TextButton text="发送erc20币" onPress={this.transferErc20} />
        </View>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  chainConfig: state.Chain.config,
});

export default connect(mapStateToProps)(HecoScreen);
